<template>
  <div class="EditDeductTax">
    <div class="cus-title"><h4>编辑抵扣金规则</h4></div>
    <div class="cus-update">
      <el-form ref="form" :model="BindForm" :rules="rules" label-width="120px" label-position="left">
        <el-form-item label="规则名称:" prop="name">
          <el-col :span="24">
            <el-input v-model="BindForm.name" :disabled="true" maxlength="20" class="cus-input" clearable />
          </el-col>
        </el-form-item>
        <el-form-item label="规则类型:" prop="type">
          <el-col :span="24">
            <el-radio v-model="BindForm.type" :disabled="true" :label="0" @change="BindForm.type=0">发放规则</el-radio>
            <el-radio v-model="BindForm.type" :disabled="true" :label="1" @change="BindForm.type=1">消耗规则</el-radio>
          </el-col>
        </el-form-item>
        <el-form-item :label="BindForm.type == 0 ? '发放方式:' : '消耗方式:'" prop="ruleMethod">
          <el-col :span="24">
            <el-radio v-model="BindForm.ruleMethod" :disabled="true" :label="0" @change="BindForm.ruleMethod=0">百分比</el-radio>
            <el-radio v-model="BindForm.ruleMethod" :disabled="true" :label="1" @change="BindForm.ruleMethod=1">固定金额</el-radio>
          </el-col>
          <el-col :span="24">
            <div v-if="BindForm.ruleMethod == 0" class="percent-div left-space">
              <el-col :span="24">
                <el-input-number v-model="BindForm.percent" :disabled="true" :controls="false" placeholder="消费金额百分比" :min="0.01" :max="100" :step="0.01" :precision="2" /> %
              </el-col>
              <el-col :span="24" style="margin-top: 15px">
                <el-alert
                  :title="BindForm.type == 0 ? '可获得消费金额的百分比抵扣金' : '可消耗消费金额的百分比抵扣金'"
                  type="info"
                  :closable="false"
                />
              </el-col>
            </div>
            <div v-if="BindForm.ruleMethod == 1" class="percent-div left-space">
              <el-col :span="24">
                <el-input-number v-model="BindForm.regular" :disabled="true" :controls="false" placeholder="固定金额元" :min="0.01" :max="9999" :step="0.01" :precision="2" /> 元
              </el-col>
              <el-col :span="24" style="margin-top: 15px">
                <el-alert
                  :title="BindForm.type == 0 ? '可获得固定金额的抵扣金' : '可消耗固定金额的抵扣金'"
                  type="info"
                  :closable="false"
                />
              </el-col>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="活动时间:" prop="times">
          <el-col :span="24">
            <el-date-picker
              v-model="BindForm.times"
              type="datetimerange"
              range-separator="至"
              start-placeholder="活动开始时间"
              end-placeholder="活动结束时间"
              align="center"
              clearable
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
            />
          </el-col>
          <el-col :span="24" style="margin-top: 15px">
            <el-alert
              :title="BindForm.type == 0 ? '活动时间内消费可获得抵扣金，时间结束后消费不能再获得抵扣金。' : '活动时间内消费可消耗抵扣金，时间结束后消费不能再消耗抵扣金。'"
              type="info"
              :closable="false"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="活动商品:" prop="goodsType">
          <el-col :span="24">
            <el-button
              v-if="BindForm.goodsType == 0"
              type="text"
              style="margin-right: 30px;"
              @click="$refs.addActGoodsDialog.show()"
            >添加活动商品</el-button>
            <el-radio-group v-model="BindForm.goodsType">
              <el-radio :label="0">部分商品</el-radio>
              <el-radio :label="1">全部商品</el-radio>
            </el-radio-group>
          </el-col>
          <el-col v-if="BindForm.goodsType == 0 && BindForm.goodsList && BindForm.goodsList.length > 0" :span="24" style="margin-top: 10px;">
            <el-table
              :data="BindForm.goodsList"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                label="商品编号"
                prop="goodsId"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column label="商品主图" align="center" :resizable="false" width="80">
                <template slot-scope="scope">
                  <TableColumnGoodsImage :src="scope.row.goodsImg" />
                </template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="goodsName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="商品类型"
                prop="type"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'lease'" type="success" size="small">租赁</el-tag>
                  <el-tag v-else-if="scope.row.type == 'sale'" type="primary" size="small">售卖</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                header-align="center"
                align="center"
                fixed="right"
                width="100"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-button size="small" type="danger" @click="deleteActGoods(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-form-item>
        <el-form-item label="活动门店:" prop="storeType">
          <el-col :span="24">
            <el-button
              v-if="BindForm.storeType == 0"
              style="margin-right: 30px;"
              type="text"
              @click="$refs.addStoreDialog.show()"
            >添加支持门店</el-button>
            <el-button
              v-else-if="BindForm.storeType == 1"
              style="margin-right: 30px;"
              type="text"
              @click="$refs.addStoreDialog.show()"
            >添加不支持门店</el-button>
            <el-radio-group v-model="BindForm.storeType">
              <el-radio :label="0">支持部分门店</el-radio>
              <el-radio :label="1">不支持的门店</el-radio>
              <el-radio :label="2">支持全部门店</el-radio>
            </el-radio-group>
          </el-col>
          <el-col v-if="BindForm.storeType != 2 && BindForm.storeList && BindForm.storeList.length > 0" :span="24" style="margin-top: 10px;">
            <el-table
              :data="BindForm.storeList"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                label="门店编号"
                prop="id"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column
                label="门店名称"
                prop="storeName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="门店地址"
                prop="address"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="操作"
                header-align="center"
                align="center"
                fixed="right"
                width="100"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-button size="small" type="danger" @click="deleteStore(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确认编辑</el-button>
        </el-form-item>
      </el-form>
    </div>

    <AddGoodsDialog ref="addActGoodsDialog" @select="addActGoods" />
    <AddStoreDialog ref="addStoreDialog" @select="addStore" />

  </div>
</template>

<script>
import { Loading } from 'element-ui'
import AddGoodsDialog from '../../../components/AddGoodsDialog/index'
import AddStoreDialog from '../../../components/AddStoreDialog/index'
import { detailRule, editRule } from '@/api/market'
import TableColumnGoodsImage from '../../../components/TableColumnGoodsImage/index'
export default {
  name: 'EditDeductTax',
  components: { TableColumnGoodsImage, AddStoreDialog, AddGoodsDialog },
  data() {
    var validateActGoods = (rule, value, callback) => {
      if (this.BindForm.goodsType === 0 && this.BindForm.goodsList.length <= 0) {
        callback(new Error('请至少添加一个活动商品'))
      } else {
        callback()
      }
    }

    var validateRuleMethod = (rule, value, callback) => {
      if (this.BindForm.ruleMethod === 0 && !this.BindForm.percent) {
        callback(new Error('请输入消费金额百分比'))
      } else if (this.BindForm.ruleMethod === 1 && !this.BindForm.regular) {
        callback(new Error('请输入固定金额元'))
      } else {
        callback()
      }
    }

    var validateStore = (rule, value, callback) => {
      if (this.BindForm.storeType !== 2 && this.BindForm.storeList.length <= 0) {
        callback(new Error('请至少添加一个门店'))
      } else {
        callback()
      }
    }
    return {
      id: null,
      BindForm: {
        name: null,
        times: null,
        goodsType: 0,
        type: 0,
        storeType: 0,
        goodsList: [],
        storeList: [],
        percent: undefined,
        regular: undefined,
        ruleMethod: 0
      },
      rules: {
        name: [{ required: true, message: '请输入规则名称', trigger: 'change' }],
        ruleMethod: [{ required: true, trigger: 'change' }, { validator: validateRuleMethod, trigger: 'blur' }],
        type: [{ required: true, trigger: 'change' }],
        times: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
        goodsType: [{ required: true, message: '请选择活动商品', trigger: 'change' }, { validator: validateActGoods, trigger: 'blur' }],
        storeType: [{ required: true, message: '请选择活动门店', trigger: 'change' }, { validator: validateStore, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.id = this.$dd(this.$route.query.p).id
    this.loadRuleDetail()
  },
  methods: {
    loadRuleDetail() {
      const loadingInstance = Loading.service({ fullscreen: true })
      const vm = this
      detailRule({
        id: vm.id
      }).then(res => {
        loadingInstance.close()
        vm.BindForm.name = res.data.data.name
        vm.BindForm.times = [res.data.data.startTime, res.data.data.endTime]
        vm.BindForm.goodsType = res.data.data.goodsType
        vm.BindForm.type = res.data.data.type
        vm.BindForm.storeType = res.data.data.storeType
        vm.BindForm.goodsList = res.data.data.goodsList
        vm.BindForm.storeList = res.data.data.storeList
        vm.BindForm.ruleMethod = res.data.data.ruleMethod
        if (vm.BindForm.ruleMethod === 0) {
          vm.BindForm.percent = res.data.data.ruleValue
        } else if (vm.BindForm.ruleMethod === 1) {
          vm.BindForm.regular = res.data.data.ruleValue
        }
      }).catch(res => {
        loadingInstance.close()
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
        vm.$store.dispatch('tagsView/delView', vm.$route)
        vm.$router.go(-1)
      })
    },
    submit() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          const loadingInstance = Loading.service({ fullscreen: true })
          const data = vm.$XEUtils.clone(vm.BindForm, true)

          if (data.goodsType === 0) {
            data.goodsList = data.goodsList.map(item => {
              return vm.$XEUtils.pick(item, ['goodsId'])
            })
          } else {
            delete data.goodsList
          }

          if (data.storeType === 0 || data.storeType === 1) {
            data.storeList = data.storeList.map(item => {
              return vm.$XEUtils.pick(item, ['id'])
            })
          } else {
            delete data.storeList
          }

          if (data.ruleMethod === 0) {
            data.ruleValue = data.percent
          } else if (data.ruleMethod === 1) {
            data.ruleValue = data.regular
          }

          delete data.percent
          delete data.regular

          editRule(data).then(res => {
            loadingInstance.close()
            vm.$message.success('编辑抵扣金活动规则成功')
            vm.$store.dispatch('tagsView/delView', vm.$route)
            vm.$router.go(-1)
          }).catch(res => {
            loadingInstance.close()
            if (res && res.data && res.data.errno !== 0) {
              this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
            }
          })
        }
      })
    },
    addActGoods(goods) {
      const vm = this

      const res = vm.$XEUtils.find(vm.BindForm.goodsList, item => item.goodsId === goods.goodsId)

      if (res) {
        vm.$message.warning('商品已存在，无需重复添加活动商品')
        return
      }

      vm.BindForm.goodsList.push(vm.$XEUtils.clone(goods, true))
      vm.$refs.form.validateField('actGoodsType')
    },
    deleteActGoods(index) {
      const vm = this

      vm.BindForm.goodsList.splice(index, 1)
      vm.$refs.form.validateField('actGoodsType')
    },
    addStore(store) {
      const vm = this

      const res = vm.$XEUtils.find(vm.BindForm.storeList, item => item.id === store.id)

      if (res) {
        vm.$message.warning('门店已存在，无需重复添加门店')
        return
      }

      vm.BindForm.storeList.push(vm.$XEUtils.clone(store, true))
      vm.$refs.form.validateField('actStoreType')
    },
    deleteStore(index) {
      const vm = this

      vm.BindForm.storeList.splice(index, 1)
      vm.$refs.form.validateField('actStoreType')
    }
  }
}
</script>

<style lang="scss" scoped>
.EditDeductTax {
  padding: 30px;
  .cus-update {
    padding: 20px 30px;
    padding-bottom: 0px;
    margin-bottom: 30px;
    border: 1px solid #eee;

    .cus-input {
      max-width: 400px;
    }
  }
}
</style>
